import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入store
import store from '@/store'
// 导入登录组件
// 路由懒加载
// import Login from '@/views/Login'
// const Login = () => {
//   return import('@/views/Login')
// }
const Login = () => import('@/views/Login')
// 导入layout组件
const Layout = () => import('@/views/Layout')
// 导入搜索页面组件
const Search = () => import('@/views/Search')
// 导入layout组件下的四个子组件
const Home = () => import('@/views/Layout/Home')
const Question = () => import('@/views/Layout/Question')
const Video = () => import('@/views/Layout/Video')
const User = () => import('@/views/Layout/User')
// 导入搜索结果组件
const SearchResult = () => import('@/views/Article/components/SearchResult')
// 文章详情组件
const Article = () => import('@/views/Article')

// 导入编辑用户资料组件
const userProfile = () => import('@/views/Layout/User/components/userProfile')
// 导入userChat组件
const userChat = () => import('@/views/Layout/User/components/userChat')

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/login', component: Login },
    {
      path: '/',
      component: Layout,
      // 配置子路由规则
      children: [
        { path: '/', component: Home, meta: { flag: true } },
        { path: '/question', component: Question, name: 'q' },
        // { path: '/question/:id', component: Question, name: 'q', props: true },
        { path: '/video', component: Video },
        { path: '/user', component: User }
      ]
    },
    { path: '/search', component: Search },
    { path: '/result', component: SearchResult },
    { path: '/article/:id', component: Article, props: true },
    { path: '/userProfile', component: userProfile },
    { path: '/userChat', component: userChat }
  ]

})
// 获取原型对象上的push函数
const originalPush = VueRouter.prototype.push
// 修改原型对象中的push方法
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}
// to 到哪去
// from 从那来  to 和 from 是路由信息对象
// next() 放行函数  ()不传参表示直接放行  ('/login') 跳转到login页面
// 需要校验权限的名单
const AuthUrls = ['/user', '/cart', '/score']
router.beforeEach((to, from, next) => {
  // 在移动端页面，如果用户登录成功,直接让用户看不到登录页面
  if (to.path === '/login' && store.state.user.tokenInfo.token) {
    return next('/')
  }
  console.log(to)
  // 如果跳转的页面是有权限的, 先看是否有token
  if (AuthUrls.includes(to.path)) {
    // 看是否有token
    const token = store.state.user.tokenInfo.token
    // 如果有token 直接放行
    if (token) {
      next()
    } else {
      // 没有token 去登录页面
      console.log(to)
      // next()传参的方式和$router.push() 传参一样的
      // next('/login')
      // 携带从哪来的地址和参数
      next({
        path: '/login',
        query: {
          backTo: to.fullPath // fullPath中有路由地址和路由参数  backTo存的就是路由地址和参数
        }
      })
    }
  } else {
    // 如果访问的页面不需要权限直接放行
    next()
  }
  /*  if (to.path === '/user') {
     console.log('验证token')
   }
   if (to.path === '/cart') {
     console.log('验证token')
   }
   if (to.path === '/score') {
     console.log('验证token')
   } */
})

export default router
